package com.zhuo.schoolproject.service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuo.schoolproject.entitys.Book;
import com.zhuo.schoolproject.entitys.File;
import com.zhuo.schoolproject.entitys.User;
import com.zhuo.schoolproject.entitys.properties.FileConfigProperties;
import com.zhuo.schoolproject.mapper.BookMapper;
import com.zhuo.schoolproject.mapper.FileMapper;
import com.zhuo.schoolproject.mapper.UserMapper;
import com.zhuo.schoolproject.service.BookService;
import com.zhuo.schoolproject.utils.FilesUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
@RequiredArgsConstructor
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    private final BookMapper bookMapper;
    private final FilesUtils filesUtils;
    private final UserMapper userMapper;
    private final FileConfigProperties fileConfigProperties;
    private final FileMapper fileMapper;

    @Override
    public SaResult saveBook(MultipartFile[] files, Book book){
        ArrayList<String> filePath = new ArrayList<>();
        for(MultipartFile file : files){
            Map<String,Object> upload = filesUtils.upload(file);
            if(upload.get("filePath")==null) return SaResult.error("请传递图片格式为.jpg...");
            filePath.add(upload.get("filePath").toString());
        }
        book.setCoverImage(filePath.get(0));
        book.setBackImage(filePath.get(1));
        //提交用户
        String loginId = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,loginId);
        User user = userMapper.selectOne(wrapper);
        book.setSubmitUser(user.getId());
//        if (user == null) return SaResult.error("未查询出当前用户");
        return bookMapper.insert(book)>0?SaResult.ok("保存成功"):SaResult.error("保存失败");
    }

    /**
     * 查询书籍内容
     * @param id
     * @return
     */
    @Cacheable(value = "bookCache",key = "#id")  //查看
    @Override
    public SaResult getBookById(Long id){
        Book book = bookMapper.selectById(id);
        if (book ==null)return SaResult.error("未查询出书籍信息");
        book.setCoverImage(book.getCoverImage().replace(fileConfigProperties.getImgAddress(),fileConfigProperties.getImgHttpAddress()));
        book.setBackImage(book.getBackImage().replace(fileConfigProperties.getImgAddress(),fileConfigProperties.getImgHttpAddress()));
        //todo书籍内容填充
        LambdaQueryWrapper<File> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(File::getBookId,book.getId());
        File file = fileMapper.selectOne(wrapper);
        book.setFileName(file);
        return SaResult.data(book);
    }

    /**
     * 保存书籍内容
     * @param file
     * @param bookId
     * @return
     */
    @Override
    public SaResult saveBookContent(MultipartFile file,Long bookId){
        Map<String,Object> upload = filesUtils.upload(file);
        if(upload.get("filePath")==null) return SaResult.error("请传递文件格式为.pdf...");
        File file1 = File.builder().bookId(bookId).pathFileName(upload.get("filePath").toString()).build();
        return fileMapper.insert(file1)>0?SaResult.ok("保存成功"):SaResult.error("保存失败");
    }
    //3.在BookServiceImpl实现类中实现getImagesNames方法
    public List<String> getImagesNames() {
        List<String> list = new ArrayList<>();
        List<Book> books = bookMapper.selectList(null);
        for (Book book : books) {
            list.add(book.getBackImage().substring(book.getBackImage().lastIndexOf("/") + 1));
            list.add(book.getCoverImage().substring(book.getCoverImage().lastIndexOf("/") + 1));
        }
        return list;
    }

    /**
     * 修改图片
     * @param files
     * @param book
     * @return
     */
    @Override
    public SaResult updateBook(MultipartFile[] files,Book book){
        Book book1 = bookMapper.selectById(book.getId());
        if (book==null)return SaResult.error("未查询出书籍信息");
        if (files!=null&&files[0]!=null){
            Map<String,Object> upload = filesUtils.upload(files[0]);
            book.setCoverImage(upload.get("filePath").toString());
        }
        if (files!=null&&files[1]!=null){
            Map<String,Object>upload = filesUtils.upload(files[1]);
            book.setCoverImage(upload.get("filePath").toString());
        }
        return bookMapper.updateById(book)>0?SaResult.ok("修改成功"):SaResult.error("修改失败");

    }

    /**
     * 修改书籍内容
     * @param file
     * @return
     */
    @Override
    public SaResult updateBookContent(MultipartFile file, Long bookId){
        LambdaQueryWrapper<File> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(File::getBookId,bookId);
        File file1 = fileMapper.selectOne(wrapper);
        if (file1 ==null)return SaResult.error("未查询出书籍内容信息");
        Map<String,Object>upload = filesUtils.upload(file);
        if (upload.get("filePath")==null) return SaResult.error("请传递文件格式为.pdf...");
        File filePath = File.builder().bookId(bookId).pathFileName(upload.get("filePath").toString()).build();
        UpdateWrapper<File> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("book_id",bookId).set("path_file_name",filePath);
        return fileMapper.update(file1,updateWrapper)>0?SaResult.ok("修改成功"):SaResult.error("修改失败");
    }

    @Override
    public SaResult deleteBook(Long id){
        Book book = bookMapper.selectById(id);
        if (book==null) return SaResult.error("未查询出书籍信息");
        //删除书籍信息
        bookMapper.selectById(id);
        filesUtils.deleteFile(book.getBackImage());//删除图片
        filesUtils.deleteFile(book.getCoverImage());//删除图片
        //删除书籍内容信息
        LambdaQueryWrapper<File> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(File::getBookId,book.getId());
        File file = fileMapper.selectOne(wrapper);
        if (file!=null){
            fileMapper.deleteById(file.getId());
            filesUtils.deleteFile(file.getPathFileName());//删除图片
        }
        return SaResult.ok("删除成功");
    }

    /**
     * 根据书籍ID查询书籍内容
     * @param id
     * @return
     */
    @Override
    public SaResult fileByBookId(Long id){
        LambdaQueryWrapper<File> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(File::getBookId,id);
        File file = fileMapper.selectOne(wrapper);
        return SaResult.data(file);
    }

    /**
     * 分页查询书籍列表
     */
    @Override
    public SaResult getBookPage(Integer pageNum, Integer pageSize, String title, String author, Integer type) {
        // 创建分页对象
        Page<Book> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (StringUtils.isNotBlank(title)) {
            wrapper.like(Book::getTitle, title);
        }
        if (StringUtils.isNotBlank(author)) {
            wrapper.like(Book::getAuthor, author);
        }
        if (type != null) {
            wrapper.eq(Book::getType, type);
        }

        // 按上传时间倒序排列
        wrapper.orderByDesc(Book::getSubmitTime);

        // 执行分页查询
        Page<Book> bookPage = bookMapper.selectPage(page, wrapper);

        // 处理图片路径（将本地路径转换为HTTP访问路径）
        List<Book> books = bookPage.getRecords().stream().map(book -> {
            if (book.getCoverImage() != null) {
                book.setCoverImage(book.getCoverImage()
                        .replace(fileConfigProperties.getImgAddress(), fileConfigProperties.getImgHttpAddress()));
            }
            if (book.getBackImage() != null) {
                book.setBackImage(book.getBackImage()
                        .replace(fileConfigProperties.getImgAddress(), fileConfigProperties.getImgHttpAddress()));
            }
            return book;
        }).collect(Collectors.toList());

        // 重新设置处理后的记录
        bookPage.setRecords(books);

        return SaResult.data(bookPage);
    }

}
